import { GlobleValue, GameState } from "./ComClass";
import { Msger } from "./Msger";

// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class WxPlatfromLogic extends cc.Component {

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        Msger.on(Msger.on_menu_more_game, this.on_menu_more_game, this);
        this.login();
    }

    start() {
        Msger.on(Msger.on_network_login_completed, this.on_network_login_completed, this);
    }
    on_network_login_completed() {
        window.wxplatform.createBannerAd();
        window.wxplatform.bannerAdHide();
    }
    update(dt) {
        let gameState = GlobleValue.gameState;
        if (gameState != GameState.Start) {
            bannerTimer += dt;
            if (bannerTimer >= 60) {
                bannerTimer = 0;
                window.wxplatform.createBannerAd();
            }
        }
    }
    async login() {
        ComLogic.Init();
    }
    private on_menu_more_game() {
        ComLogic.handleMoreGameButton();
    }
}
let bannerTimer = 0;
/*分享逻辑*/
export module ComLogic {
    export async function shareGoto(key, needgroup = true, params: any = null): Promise<boolean> {
        /* if (GlobleValue.gameSwitch && needgroup) {
            return await createRewardedVideoAd();
        }
        if (GlobleValue.ipSwitch && needgroup) {
            let ret = await createRewardedVideoAd();
            if (ret == null) {
                return await shareto(key, needgroup, params);
            }
            return ret;
        }
        return await shareto(key, needgroup, params); */
        return new Promise<boolean>((resolve,reject)=>{
            resolve(true);
        });
    }
    let group_notice = "无效的目标";
    export async function shareto(key, needgroup = true, params: any = null): Promise<boolean> {
        shareNeedGroup = needgroup;
        let ret = await sharetohandle(key, needgroup, params);
        switch (ret.success) {
            case 0://失败
                if (ret.msg) {
                    let agree = await window.wxplatform.showMessageBoxOKCancel("失败", ret.msg, "确定");
                    if (agree) {
                        return await shareto(key, needgroup, params);
                    } else {
                        return false;
                    }
                }
                return false;
            case 1://成功
                Msger.emit(Msger.on_ui_show_message, "成功获得！");
                return true;
        }
    }
    //needgroup必须是否为群
    export async function sharetohandle(sharekey, needgroup = true, params: any = null): Promise<any> {
        if (!window.wxplatform.inWxgame()) {
            return 1;
        }
        let array = shareDataArray[sharekey];
        console.log('share handle:', sharekey, array);
        if (!array) {
            array = shareDataArray["forward"];
        }
        let sharedata = getOneInArray(array);
        let addparams = "shareid=" + sharedata.id;
        addparams += "&time=" + Date.now();
        addparams += "&sharekey=" + sharekey;
        if (params) {
            for (let key in params) {
                addparams += "&" + key + "=" + params[key];
            }
        }
        shareHideOutTimer = new Date().getTime();
        Msger.emit(Msger.on_show_block_shareui);
        return new Promise<number>((resolve, reject) => {
            shareBackResolve[sharekey] = resolve;
            window.wxplatform.shareAppMessage(sharedata.text, sharedata.pic, addparams);
        });
    }
    let shareBackResolve = {};
    let shareHideOutTimer = 0;
    let shareSuccessCount = 0;
    let shareNeedGroup = false;
    /* Msger.on(Msger.on_hide_block_shareui, () => {
        shareBackResolve = null;
        window.wxplatform.offShow(onShowBack);
    }); */
    let shareSwitch = 2;//2 点回去 ，1概率
    async function onShowBack2(res) {
        console.log("onShowBack res ", res);
        if (res.query.time) {
            let success = -1;//0失败 1成功
            let msg = null;
            let sharekey = res.query.sharekey;
            let timespan = Date.now() - parseInt(res.query.time);
            if (timespan > 10 * 1000 * 60) {
                //没反应
            } else if (res) {
                if (res.scene) {
                    let scenestr = res.scene + '';
                    //这是群
                    if (scenestr == '1044' || scenestr == '1008') {
                        //success = 1;
                        if (res.shareTicket) {
                            let shareinfo = await window.wxplatform.getShareInfo(res.shareTicket);
                            success = 1;
                        }
                    } else if (scenestr == '1007') {
                        success = 0;
                        msg = "点击个人分享链接不会获得奖励，请分享到微信群吧！";
                    }
                }
            }
            if (shareBackResolve[sharekey] && success != -1) {
                shareBackResolve[sharekey]({ success: success, msg: msg });
                Msger.emit(Msger.on_hide_block_shareui);
            }
            console.log("shareBackResolve ", success);
        }
    }
    function onShowBack1(res) {
        window.wxplatform.offShow(onShowBack2);
        console.log("onShowBack timer = ", shareHideOutTimer, "shareNeedGroup =");
        let timespan = new Date().getTime() - shareHideOutTimer;
        let sharekey = res.query.sharekey;
        if (shareBackResolve[sharekey]) {
            let success = 0;//0失败 1成功
            if (shareNeedGroup) {
                console.log("timespan = ", timespan);
                if (timespan > 2000) {
                    let lastsharetimeday = localStorage.getItem("lastsharetimeday");
                    let day = new Date().getDate().toString();
                    if (day != lastsharetimeday) {
                        success = 1;
                        shareSuccessCount = 0;
                    } else {
                        let r = 1;
                        switch (shareSuccessCount) {
                            case 0:
                                r = 0.5;
                                break;
                            case 1:
                                r = 0.7;
                                break;
                            case 2:
                                r = 1;
                                shareSuccessCount = -1;
                                break;
                        }
                        shareSuccessCount += 1;
                        success = Math.random() < r ? 1 : 0;
                    }
                    console.log("shareSuccessCount=", shareSuccessCount, "lastsharetimeday=", lastsharetimeday, "day", day);
                    lastsharetimeday = day;
                    localStorage.setItem("lastsharetimeday", lastsharetimeday);
                }
            } else {
                success = 1;
            }
            console.log("shareBackResolve ", { success: success });
            let msg = null;
            if (success == 0) {
                msg = group_notice;
            }
            shareBackResolve[sharekey]({ success: success, msg: msg });
            shareBackResolve = null;
        }
    }
    let shareDataArray = {};
    class shareDataItem {
        id: number;
        type: string;
        pic: string;
        text: string;
    }
    /*初始化，并且login一下*/
    export async function Init() {
        window.wxplatform.onShow(handleLaunchAndOnShow);
        window.wxplatform.showLoading("请稍候");
        let logindata = await window.wxplatform.login();
        console.log(logindata);
        
        /* let launchOption = window.wxplatform.getLaunchOptionsSync();
        let shareId = null;
        let inviteId = null;
        if (launchOption.query) {
            shareId = launchOption.query.shareid;
            if (launchOption.query.inviteId) {
                inviteId = Math.floor(launchOption.query.inviteId);
            }
        }
        let userInfo: any = {};
        if (!window.wxplatform.inWxgame()) {
            userInfo = { code: "stgame2048test" };
        } else {
            let logindata = await window.wxplatform.login();
            let setting = await window.wxplatform.getSetting();
            if (setting) {
                if (setting.authSetting['scope.userInfo']) {
                    userInfo = await window.wxplatform.getUserInfo();
                    console.log(userInfo);
                }
            }
            userInfo.code = logindata.code;
            window.wxplatform.onShareAppMessage(onShareAppMessageCallback);
        }
        
        let ret
        ret = await new Network.Login().Post({
            code: userInfo.code,
            nickName: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl,
            city: userInfo.city,
            gender: userInfo.gender,
            language: userInfo.language,
            province: userInfo.province,
            encryptedData: userInfo.encryptedData,
            iv: userInfo.iv,
            shareId: shareId,
            query: launchOption.query,
            inviteUser: inviteId,
            referrer: launchOption.referrerInfo
        });
        if (!ret) {
            return await Init();
        } */
        
        /*获得登录成功*/
        /* if (ret.data) {
            GlobleValue.gameSwitch = ret.data.config.switch == 0;//0审核 1正常
            GlobleValue.ipSwitch = ret.data.config.ip == 1;//0不限制 1限制		
            shareSwitch = ret.data.config.sharetype;//2 点回去 ，1概率
            if (shareSwitch == 1) {
                window.wxplatform.onShow(onShowBack1);
            } else {
                window.wxplatform.onShow(onShowBack2);
            }
            //建立分享数据组
            shareDataArray = ret.data.share;
            hutuiArray = ret.data.promote.hutui;
            moreGame = ret.data.promote.moregame[0];
            dockArray = ret.data.promote.dock;
            if (dockArray) {
                dockArray = dockArray.sort((a, b) => { return b.weight - a.weight });
            }
            //默认失败的数据
            group_notice = ret.data.group_notice;
            
        } */
        Msger.emit(Msger.on_network_login_completed);
        window.wxplatform.showShareMenu();
        window.wxplatform.hideLoading();
    }

    export function handleLaunchAndOnShow(res) {
        if (res.query) {
            if (res.query.shareid) {
                console.log("handleLaunchAndOnShow", res);
            }
        }
        if (res.referrerInfo) {

        }
    }
    export let dockArray: { appid, dot, icon, id, img, path, status, weight, type }[] = null;
    function onShareAppMessageCallback(): any {
        let array = shareDataArray["forward"];
        let sharedata = getOneInArray(array);
        let addparams = "shareid=" + sharedata.id;
        return {
            title: sharedata.text,
            imageUrl: sharedata.pic,
            query: addparams
        }
    }
    function getOneInArray(array: any[]) {
        return array[Math.floor(Math.random() * array.length)];
    }
    export let hutuiArray: any[] = null;
    export function navigateToOther(index) {
        let appid = hutuiArray[index].appId;
        let img = hutuiArray[index].img;
        let path = hutuiArray[index].path;
        //type  （0表示正常逻辑  1表示直接弹二维码图）  
        let type = hutuiArray[index].type;
        window.wxplatform.navigateToMiniProgram(appid, path, img, type == 1);
    }
    export function getNavigateToOtherIcon(): [number, string] {
        let index = -1;
        let icon = null;
        //weight  （随机权重）
        if (!hutuiArray) {
            return [index, icon];
        }
        if (hutuiArray.length) {
            let sumweight = 0;
            for (let item of hutuiArray) {
                sumweight += item.weight;
            }
            let random = Math.random() * sumweight;
            sumweight = 0;
            for (let item of hutuiArray) {
                sumweight += item.weight;
                if (random < sumweight) {
                    index = hutuiArray.indexOf(item);
                    break;
                }
            }
            //index = Math.floor(Math.random() * hutuiArray.length);
            icon = hutuiArray[index].icon;
        }
        return [index, icon];
    }
    /*视频广告处理逻辑*/
    export async function createRewardedVideoAd(): Promise<boolean> {
        bannerTimer = 0;
        if (window.wxplatform.inWxgame()) {
            window.wxplatform.showLoading("请稍后");
            //return ComLogic.shareto(key, needgroup);
            //第一个提交
            let ret = false;
            let vad = await window.wxplatform.createRewardedVideoAd();
            window.wxplatform.hideLoading();
            /* if (!vad) {
                if (GlobleValue.ipSwitch) {
                    return ComLogic.shareto(key, needgroup);
                } else {
                    Msger.emit(Msger.on_ui_show_message, "现在没有广告可供欣赏");
                    return false;
                }
            } */
            return new Promise<boolean>((resolve, rej) => {
                if (vad) {
                    vad.show().catch(err => {
                        console.log('RewardedVideoAdShow err', err);
                        resolve(null);
                    });
                    vad.onClose(res => {
                        // 用户点击了【关闭广告】按钮
                        // 小于 2.1.0 的基础库版本，res 是一个 undefined
                        if (res && res.isEnded || res === undefined) {
                            // 正常播放结束，可以下发游戏奖励
                            ret = true;
                        }
                        else {
                            // 播放中途退出，不下发游戏奖励
                            ret = false;
                        }
                        resolve(ret);
                    })
                } else {
                    Msger.emit(Msger.on_ui_show_message, "现在没有广告可供欣赏");
                    //MsgerHandler.emit(FishC.MsgerNames.ShowTipBar, "现在没有广告可供欣赏");                    
                    resolve(false);
                }
            });
        }
        return new Promise<boolean>((res, rej) => {
            //Msger.emit(Msger.on_ui_show_message,"没在微信里，自动成功！");
            res(true);
        });
    }
    // 更多游戏的相关处理
    export let moreGame;
    export function handleMoreGameButton() {
        if (moreGame) {
            let appid = moreGame.appId;
            let img = moreGame.img;
            let path = moreGame.path;
            //type  （0表示正常逻辑  1表示直接弹二维码图）  
            let type = moreGame.type;
            window.wxplatform.navigateToMiniProgram(appid, path, img, type == 1);
            return true;
        } else {
            return false;
        }
    }
}